ass Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) 
    {
        if (root == nullptr)
        {
            return nullptr;
        }

        // 层序遍历 首先定义
        queue<Node*> que;
        Node* cur = root;
        que.push(cur);
        int levelsize = 1;
        while(!que.empty())
        {
            if (levelsize ) 
            {
                cur = que.front();
                que.pop();
                if (levelsize == 1)
                {
                    cur->next = nullptr;
                }
                else
                {
                    cur->next = que.front();
                }
                levelsize--;
                if (cur->left)
                {
                    que.push(cur->left);
                }
                if (cur->right)
                {
                    que.push(cur->right);
                }
            }
            else
            {
                levelsize = que.size();
            }
        }
        return root;
    }
};
